import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Progress } from './ui/progress';
import { Badge } from './ui/badge';
import { Keyboard, Timer, Target, RotateCcw, Zap, CheckCircle } from 'lucide-react';
import { TestResult } from '../types';

interface TypingSpeedTestProps {
  onComplete: (result: TestResult) => void;
}

const sampleTexts = [
  "人工智能技术正在快速发展，它将改变我们的生活方式和工作方式。机器学习和深度学习算法使得计算机能够从数据中学习并做出智能决策。",
  "现代社会信息技术的发展日新月异，互联网已经成为人们日常生活中不可或缺的一部分。云计算、大数据、物联网等技术正在重塑整个社会。",
  "教育是社会发展的基石，优质的教育资源应该让每个人都能享受到。在线教育平台的兴起为知识传播提供了新的渠道和方式。",
  "环境保护是当今世界面临的重大挑战之一。可持续发展理念要求我们在追求经济增长的同时，也要保护好我们赖以生存的地球环境。",
  "科技创新是推动经济社会发展的重要动力。从移动支付到共享经济，从人工智能到区块链技术，创新正在深刻改变着我们的世界。"
];

type TestState = 'ready' | 'testing' | 'complete';

export function TypingSpeedTest({ onComplete }: TypingSpeedTestProps) {
  const [state, setState] = useState<TestState>('ready');
  const [testText, setTestText] = useState('');
  const [userInput, setUserInput] = useState('');
  const [startTime, setStartTime] = useState<number>(0);
  const [endTime, setEndTime] = useState<number>(0);
  const [timeLeft, setTimeLeft] = useState(60); // 60 seconds test
  const [timerInterval, setTimerInterval] = useState<NodeJS.Timeout | null>(null);
  
  const inputRef = useRef<HTMLTextAreaElement>(null);

  const testDuration = 60; // seconds

  const startTest = useCallback(() => {
    const randomText = sampleTexts[Math.floor(Math.random() * sampleTexts.length)];
    setTestText(randomText);
    setUserInput('');
    setState('testing');
    const now = Date.now();
    setStartTime(now);
    setEndTime(0);
    setTimeLeft(testDuration);
    
    const interval = setInterval(() => {
      setTimeLeft(prev => {
        if (prev <= 1) {
          clearInterval(interval);
          setState('complete');
          setEndTime(Date.now());
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
    
    setTimerInterval(interval);
    
    // Focus input
    setTimeout(() => {
      inputRef.current?.focus();
    }, 100);
  }, []);

  const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    const input = e.target.value;
    setUserInput(input);
    
    // Check if test is complete (user typed the entire text)
    if (input.length >= testText.length) {
      if (timerInterval) {
        clearInterval(timerInterval);
      }
      setState('complete');
      setEndTime(Date.now());
    }
  };

  const resetTest = () => {
    setState('ready');
    setTestText('');
    setUserInput('');
    setStartTime(0);
    setEndTime(0);
    setTimeLeft(testDuration);
    if (timerInterval) {
      clearInterval(timerInterval);
      setTimerInterval(null);
    }
  };

  const getStats = () => {
    // 计算实际用时（秒）
    let timeElapsed: number;
    if (endTime > 0) {
      timeElapsed = (endTime - startTime) / 1000;
    } else if (startTime > 0) {
      timeElapsed = (Date.now() - startTime) / 1000;
    } else {
      timeElapsed = 0.1; // 避免除零
    }
    
    timeElapsed = Math.max(0.1, timeElapsed); // 最少0.1秒
    
    const charactersTyped = userInput.length;
    
    // 计算正确字符数 - 逐字符对比
    let correctCharacters = 0;
    for (let i = 0; i < Math.min(userInput.length, testText.length); i++) {
      if (userInput[i] === testText[i]) {
        correctCharacters++;
      }
    }
    
    // 计算单词数（中文按字符计算，英文按单词计算）
    const wordsTyped = userInput.trim().length; // 中文以字符为单位
    
    // WPM计算 - 标准公式：(总字符数 / 5) / 分钟数
    // 这里使用实际字符数，因为是中文输入
    const wpm = Math.round((charactersTyped / 5) / (timeElapsed / 60));
    
    // CPM计算 - 每分钟字符数
    const cpm = Math.round(charactersTyped / (timeElapsed / 60));
    
    // 准确率计算 - 考虑缺失的字符
    let accuracy: number;
    if (charactersTyped === 0) {
      accuracy = 0;
    } else {
      accuracy = Math.round((correctCharacters / charactersTyped) * 100);
    }
    
    // 净WPM计算 - 扣除错误字符的影响
    const errorCharacters = charactersTyped - correctCharacters;
    const netWpm = Math.max(0, Math.round(((correctCharacters / 5) - (errorCharacters / 5)) / (timeElapsed / 60)));
    
    return { 
      wpm: Math.max(0, Math.min(wpm, 999)), 
      netWpm: Math.max(0, Math.min(netWpm, 999)),
      cpm: Math.max(0, Math.min(cpm, 9999)), 
      accuracy: Math.max(0, Math.min(accuracy, 100)), 
      wordsTyped: Math.max(0, wordsTyped), 
      charactersTyped: Math.max(0, charactersTyped), 
      correctCharacters: Math.max(0, correctCharacters), 
      errorCharacters: Math.max(0, errorCharacters),
      timeElapsed: Math.max(0, timeElapsed)
    };
  };

  const getScore = () => {
    const { netWpm, accuracy } = getStats();
    
    // 基础分数基于净WPM（扣除错误后的WPM）
    let score = netWpm;
    
    // 准确率奖励/惩罚
    if (accuracy >= 98) {
      score *= 1.2; // 98%以上准确率，20%奖励
    } else if (accuracy >= 95) {
      score *= 1.1; // 95%以上准确率，10%奖励
    } else if (accuracy >= 90) {
      score *= 1.05; // 90%以上准确率，5%奖励
    } else if (accuracy < 80) {
      score *= 0.8; // 80%以下准确率，20%惩罚
    } else if (accuracy < 85) {
      score *= 0.9; // 85%以下准确率，10%惩罚
    }
    
    // 确保分数在合理范围内
    const finalScore = Math.max(0, Math.min(100, Math.round(score)));
    return finalScore;
  };

  const getRating = () => {
    const { netWpm } = getStats();
    if (netWpm >= 80) return { text: '大师级', color: 'text-purple-500' };
    if (netWpm >= 60) return { text: '专业级', color: 'text-yellow-500' };
    if (netWpm >= 45) return { text: '高级', color: 'text-green-500' };
    if (netWpm >= 30) return { text: '中级', color: 'text-blue-500' };
    if (netWpm >= 20) return { text: '初级', color: 'text-gray-500' };
    return { text: '新手', color: 'text-orange-500' };
  };

  const renderTextWithHighlight = () => {
    return testText.split('').map((char, index) => {
      let className = 'text-muted-foreground';
      
      if (index < userInput.length) {
        if (userInput[index] === char) {
          className = 'text-green-600 bg-green-100 dark:bg-green-900/30';
        } else {
          className = 'text-red-600 bg-red-100 dark:bg-red-900/30';
        }
      } else if (index === userInput.length) {
        className = 'bg-blue-200 dark:bg-blue-800 text-foreground animate-pulse';
      }
      
      return (
        <span key={index} className={className}>
          {char}
        </span>
      );
    });
  };

  const handleComplete = () => {
    const stats = getStats();
    const score = getScore();
    const testDurationUsed = Math.round(stats.timeElapsed);
    
    const result: TestResult = {
      id: Date.now().toString(),
      testType: 'typing',
      score: score,
      completedAt: new Date(),
      duration: Math.max(1, testDurationUsed),
      details: {
        wpm: stats.wpm,
        netWpm: stats.netWpm,
        cpm: stats.cpm,
        accuracy: stats.accuracy,
        wordsTyped: stats.wordsTyped,
        charactersTyped: stats.charactersTyped,
        correctCharacters: stats.correctCharacters,
        errorCharacters: stats.errorCharacters,
        timeElapsed: stats.timeElapsed,
        rating: getRating().text,
        testText: testText.length > 0 ? (testText.substring(0, 100) + (testText.length > 100 ? '...' : '')) : '无测试文本',
        userInput: userInput.length > 0 ? (userInput.substring(0, 100) + (userInput.length > 100 ? '...' : '')) : '无输入内容',
        
        // 兼容性字段
        totalQuestions: 1,
        correctAnswers: stats.accuracy >= 85 ? 1 : 0, // 准确率>=85%视为正确
        averageTimePerQuestion: stats.timeElapsed,
        
        // 打字特有字段
        averageTime: stats.timeElapsed,
        totalRounds: 1
      }
    };
    onComplete(result);
  };

  useEffect(() => {
    return () => {
      if (timerInterval) {
        clearInterval(timerInterval);
      }
    };
  }, [timerInterval]);

  if (state === 'complete') {
    const stats = getStats();
    const rating = getRating();
    
    return (
      <div className="max-w-4xl mx-auto space-y-6">
        <Card>
          <CardHeader className="text-center">
            <CardTitle className="flex items-center justify-center gap-2">
              <CheckCircle className="w-6 h-6 text-green-500" />
              测试完成！
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="text-center space-y-4">
              <div className="text-6xl font-bold text-primary">
                {stats.netWpm}
              </div>
              <div className="text-xl text-muted-foreground">净WPM (扣除错误)</div>
              <div className={`text-xl font-semibold ${rating.color}`}>
                {rating.text}
              </div>
              <div className="text-lg">
                最终得分: <span className="font-bold text-primary">{getScore()}</span>
              </div>
            </div>

            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="text-center p-4 bg-muted rounded-lg">
                <div className="text-2xl font-bold">{stats.wpm}</div>
                <div className="text-sm text-muted-foreground">总WPM</div>
              </div>
              <div className="text-center p-4 bg-muted rounded-lg">
                <div className="text-2xl font-bold">{stats.netWpm}</div>
                <div className="text-sm text-muted-foreground">净WPM</div>
              </div>
              <div className="text-center p-4 bg-muted rounded-lg">
                <div className="text-2xl font-bold">{stats.accuracy}%</div>
                <div className="text-sm text-muted-foreground">准确率</div>
              </div>
              <div className="text-center p-4 bg-muted rounded-lg">
                <div className="text-2xl font-bold">{Math.round(stats.timeElapsed)}s</div>
                <div className="text-sm text-muted-foreground">用时</div>
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
              <div className="text-center p-4 bg-muted rounded-lg">
                <div className="text-xl font-bold">{stats.charactersTyped}</div>
                <div className="text-sm text-muted-foreground">总字符数</div>
              </div>
              <div className="text-center p-4 bg-muted rounded-lg">
                <div className="text-xl font-bold text-green-600">{stats.correctCharacters}</div>
                <div className="text-sm text-muted-foreground">正确字符</div>
              </div>
              <div className="text-center p-4 bg-muted rounded-lg">
                <div className="text-xl font-bold text-red-600">{stats.errorCharacters}</div>
                <div className="text-sm text-muted-foreground">错误字符</div>
              </div>
              <div className="text-center p-4 bg-muted rounded-lg">
                <div className="text-xl font-bold">{stats.cpm}</div>
                <div className="text-sm text-muted-foreground">CPM</div>
              </div>
            </div>

            <div className="flex gap-4">
              <Button 
                onClick={resetTest} 
                variant="outline" 
                className="flex-1 border-2 border-slate-300 hover:border-blue-500 hover:bg-blue-50 hover:text-blue-700 transition-all duration-200"
              >
                <RotateCcw className="w-4 h-4 mr-2" />
                重新测试
              </Button>
              <Button 
                onClick={handleComplete} 
                className="flex-1 bg-gradient-to-r from-green-500 to-emerald-500 text-white hover:from-green-600 hover:to-emerald-600 shadow-md hover:shadow-lg transition-all duration-200"
              >
                保存结果
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto space-y-6">
      {state === 'testing' && (
        <Card>
          <CardContent className="pt-6">
            <div className="flex justify-between items-center mb-4">
              <div className="flex items-center gap-4">
                <div className="flex items-center gap-2">
                  <Timer className="w-4 h-4" />
                  <span className="font-mono text-lg">{timeLeft}s</span>
                </div>
                <Badge variant={timeLeft > 30 ? 'secondary' : timeLeft > 10 ? 'default' : 'destructive'}>
                  {timeLeft > 30 ? '充足时间' : timeLeft > 10 ? '注意时间' : '时间紧急'}
                </Badge>
              </div>
              <div className="flex items-center gap-4">
                {userInput.length > 0 && (
                  <>
                    <div className="text-sm">
                      <Zap className="w-4 h-4 inline mr-1" />
                      {getStats().netWpm} 净WPM
                    </div>
                    <div className="text-sm">
                      <Target className="w-4 h-4 inline mr-1" />
                      {getStats().accuracy}% 准确率
                    </div>
                  </>
                )}
              </div>
            </div>
            <Progress value={testDuration > 0 ? ((testDuration - timeLeft) / testDuration) * 100 : 0} />
          </CardContent>
        </Card>
      )}

      <Card>
        {state === 'ready' && (
          <>
            <CardHeader className="text-center">
              <CardTitle className="flex items-center justify-center gap-2">
                <Keyboard className="w-6 h-6 text-blue-500" />
                打字速度测试
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-6">
              <div className="text-center space-y-4">
                <p className="text-muted-foreground">
                  测试将持续 {testDuration} 秒，请尽可能快速且准确地输入显示的文本。
                </p>
                <div className="flex justify-center gap-4">
                  <Badge variant="outline">
                    <Timer className="w-3 h-3 mr-1" />
                    {testDuration} 秒
                  </Badge>
                  <Badge variant="outline">
                    <Target className="w-3 h-3 mr-1" />
                    准确性优先
                  </Badge>
                  <Badge variant="outline">
                    <Zap className="w-3 h-3 mr-1" />
                    速度重要
                  </Badge>
                </div>
                <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 text-sm text-blue-800">
                  <h4 className="font-semibold mb-2">计分说明：</h4>
                  <ul className="text-left space-y-1">
                    <li>• <strong>净WPM</strong>：扣除错误字符后的每分钟字数，更准确反映打字水平</li>
                    <li>• <strong>准确率奖励</strong>：98%以上+20%，95%以上+10%，90%以上+5%</li>
                    <li>• <strong>准确率惩罚</strong>：85%以下-10%，80%以下-20%</li>
                    <li>• <strong>WPM计算</strong>：(字符数 ÷ 5) ÷ 分钟数（标准打字测试公式）</li>
                  </ul>
                </div>
              </div>
              <div className="text-center">
                <Button 
                  size="lg" 
                  onClick={startTest}
                  className="bg-gradient-to-r from-slate-400 to-gray-500 hover:from-slate-500 hover:to-gray-600 text-white shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-300 border-0 min-w-[140px] h-12"
                >
                  <Keyboard className="w-5 h-5 mr-2" />
                  开始测试
                </Button>
              </div>
            </CardContent>
          </>
        )}

        {state === 'testing' && (
          <CardContent className="space-y-6">
            <div className="space-y-4">
              <h3 className="font-semibold">请输入以下文本：</h3>
              <div className="p-4 bg-muted rounded-lg font-mono text-lg leading-relaxed select-none">
                {renderTextWithHighlight()}
              </div>
            </div>

            <div className="space-y-2">
              <label className="font-semibold">您的输入：</label>
              <textarea
                ref={inputRef}
                value={userInput}
                onChange={handleInputChange}
                className="w-full h-32 p-4 border rounded-lg font-mono text-lg resize-none focus:outline-none focus:ring-2 focus:ring-primary"
                placeholder="开始输入..."
                disabled={state !== 'testing'}
              />
            </div>

            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-center">
              <div className="p-3 bg-muted rounded-lg">
                <div className="text-xl font-bold">{userInput.length}</div>
                <div className="text-sm text-muted-foreground">已输入字符</div>
              </div>
              <div className="p-3 bg-muted rounded-lg">
                <div className="text-xl font-bold">{testText.length}</div>
                <div className="text-sm text-muted-foreground">总字符数</div>
              </div>
              <div className="p-3 bg-muted rounded-lg">
                <div className="text-xl font-bold">{testText.length > 0 ? Math.round((userInput.length / testText.length) * 100) : 0}%</div>
                <div className="text-sm text-muted-foreground">完成进度</div>
              </div>
              <div className="p-3 bg-muted rounded-lg">
                <div className="text-xl font-bold">{getStats().netWpm}</div>
                <div className="text-sm text-muted-foreground">当前净WPM</div>
              </div>
            </div>
          </CardContent>
        )}
      </Card>

      <Card>
        <CardContent className="pt-6">
          <h3 className="font-semibold mb-2">测试说明</h3>
          <ul className="text-sm text-muted-foreground space-y-1">
            <li>• 测试时长为 {testDuration} 秒</li>
            <li>• 输入错误的字符会被标记为红色</li>
            <li>• 准确性比速度更重要，错误会显著影响得分</li>
            <li>• <strong>净WPM</strong> = 扣除错误后的每分钟字数，更准确反映打字水平</li>
            <li>• <strong>总WPM</strong> = 包含错误的每分钟字数</li>
            <li>• 绿色表示正确，红色表示错误，蓝色表示当前位置</li>
          </ul>
        </CardContent>
      </Card>
    </div>
  );
}